package com.cq.digitalemployee.user.controller;

import com.cq.digitalemployee.result.BaseResult;
import com.cq.digitalemployee.result.FailureResult;
import com.cq.digitalemployee.result.SuccessResult;
import com.cq.digitalemployee.shiro.token.TokenEntity;
import com.cq.digitalemployee.shiro.token.service.TokenService;
import com.cq.digitalemployee.shiro.utils.PasswordUtil;
import com.cq.digitalemployee.user.entity.dto.LoginDto;
import com.cq.digitalemployee.user.entity.po.SysUser;
import com.cq.digitalemployee.user.service.SysUserService;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zzz
 */
@RestController
@RequestMapping("/")
public class LoginController {

    @Autowired
    TokenService tokenService;

    @Autowired
    SysUserService userService;

    @PostMapping("login")
    public BaseResult login(@Validated LoginDto loginDto) {
        BaseResult result;
        try {
            SysUser loginUser = userService.findByLoginName(loginDto.getLoginName());
            if (loginUser == null) {
                throw new UnknownAccountException();
            }
            String accessPassword = PasswordUtil.encryptPassword(loginDto.getPassword());
            if (!accessPassword.equals(loginUser.getPassword())) {
                throw new IncorrectCredentialsException();
            }
            TokenEntity tokenEntity = tokenService.createToken(loginUser.getId());

            Map<String, String> tokenMap = new HashMap<>(1);
            tokenMap.put("token", tokenEntity.getToken());
            result = new SuccessResult();
            result.setMsg("登陆成功");
            result.setData(tokenMap);
        } catch (UnknownAccountException e) {
            result = new FailureResult();
            result.setMsg("账号不存在");
        } catch (IncorrectCredentialsException e) {
            result = new FailureResult();
            result.setMsg("密码错误");
        } catch (Exception exception) {
            exception.printStackTrace();
            result = new FailureResult();
            result.setMsg("发生错误:" + exception);
        }
        return result;
    }

    @GetMapping("logout")
    public BaseResult logout(){
        BaseResult result = new SuccessResult();
        result.setMsg("登出成功");
        return result;
    }
}
